﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.AddIn.Hosting;
using System.Collections.ObjectModel;
using Exceptions;
using HostView;

namespace AddIns
{
    internal class AddInManager
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private AddInToken asn1Token,xmhegToken,txtToken;

        internal AddInManager()
        {
            SetupAddIns();
            
        }
        
        internal void SetupAddIns()
        {
            
            // Set the add-ins discovery root directory to be the current directory
            string addinRoot = Environment.CurrentDirectory;

            // Rebuild the add-ins cache and pipeline components cache.
            AddInStore.Rebuild(addinRoot);
            AddInToken.EnableDirectConnect = true;

            // Get registerd add-ins of type SimpleAddInHostView
            var addins = AddInStore.FindAddIns(typeof(CoreHostView), addinRoot);
            
            foreach (AddInToken addinToken in addins)
            {

                switch (addinToken.Name)
                {
                    case("ASN1Decoder"):
                        asn1Token = addinToken;
                        break;
                    case ("XMHEGDecoder"):
                        xmhegToken = addinToken;
                        break;
                    case ("TextDecoder"):
                        txtToken = addinToken;
                        break;

                }

                log.Info(String.Format("Found decoder {0} Version {1}", addinToken.Name, addinToken.Version));
                

            }
        }

        private CoreHostView asn1Decoder;

        internal CoreHostView ASN1Decoder
        {
            get
            {
                try
                {
                    return asn1Decoder ??
                           (asn1Decoder = (asn1Token.Activate<CoreHostView>(AppDomain.CurrentDomain )));
                }
                catch (NullReferenceException e)
                {
                    throw new OpenMhegException("Can't find ASN1 Decoder plugin", e);
                }
            }
        }


        internal CoreHostView GetXMHEGDecoder()
        {
            return null;
        }

        internal CoreHostView GetTextDecoder()
        {
            return null;
        }
    
    }
}
